package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.bookstore.bean.NewBookReadBean;
import com.ciwong.epaper.modules.bookstore.bean.NewBookReadNetBean;
import com.ciwong.epaper.modules.epaper.adapter.NewBookReadAdapter;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.GradeBean;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.NewReadBookNetResultBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.NewBookDetailH5Activity;
import com.ciwong.epaper.modules.epaper.ui.NewContentActivity2;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.interactivetutorial.InteractiveTutorialCordovaActivity;
import com.ciwong.epaper.modules.me.adapter.BookDeskGridAdapter;
import com.ciwong.epaper.modules.me.adapter.BookReadCategoryGridAdapter;
import com.ciwong.epaper.modules.me.bean.CategoryBean;
import com.ciwong.epaper.modules.me.bean.EpaperInfoGradeNameBean;
import com.ciwong.epaper.modules.me.bean.InteractionCategoryBean;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.utils.GsonUtil;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.NoScrollGridView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 标签书籍页面
 * 书籍UI和书桌旧版用的是同一个UI布局和ADAPTER  修改的时候需要注意一下
 */

public class NewBookReadActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    private RecyclerView mRvBookDesk;
    private NewBookReadAdapter mBookDeskAdapter;
    private List<NewBookReadBean> mEpaperInfoList = new ArrayList<>();
    private SwipeToLoadLayout mSwipeToLoadLayout;
    private int mBookmarkId;
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private String mBookmarkTitle;
    private boolean mIsRefesh;
    private LinearLayout list_nodata;
    private ViewGroup listviewgroup;
    private Button btn_retry;
    private NoScrollGridView grand_name_grid;
    private BookDeskGridAdapter bookDeskGridAdapter;
    private List<EpaperInfoGradeNameBean> epaperInfoGradeNameBeans = new ArrayList<>();
    private int gradeId;

    //new
    private boolean isShowSubCategory = false;
    private NoScrollGridView grand_category_grid;
    private List<CategoryBean> mInfoGradeCategoryBean = new ArrayList<>();
    private BookReadCategoryGridAdapter bookCategoryDridAdapter;
    private int mBookTypeId = 0;
    //服务器请求
    private int categoryId = 0;
    private int subCategoryId = 0;

    private DownLoadInfo mDownLoadInfo = new DownLoadInfo();

    private NewBookReadBean mCurrentNewBookReadBean;

    @Override
    protected int setView() {
        return R.layout.fragment_book_desk;
    }

    @Override
    protected void findViews() {
        mRvBookDesk = findViewById(R.id.swipe_target);
        mSwipeToLoadLayout = findViewById(R.id.swipe_toLoad_layout);
        list_nodata = findViewById(R.id.ll_no_net);
        listviewgroup = findViewById(R.id.listviewgroup);
        btn_retry = findViewById(R.id.btn_retry);
        grand_name_grid = findViewById(R.id.grand_name_grid);
        grand_category_grid = findViewById(R.id.grand_category_grid);
        findViewById(R.id.rl_top_chose).setVisibility(View.VISIBLE);
        findViewById(R.id.rl_top_sub_category_layout).setVisibility(View.VISIBLE);
    }

    @Override
    protected void initEvent() {
        setImgRightBtn(R.mipmap.icon_search);
        hideRightImgBtn();
        setImgRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                EpaperJumpManager.jumpToSerachBook(R.string.go_back, NewBookReadActivity.this, RequestCode.BookDeskResquestCode.REQ_CODE_TO_SEARCH_BOOK);
            }
        });
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);
        btn_retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadData();
            }
        });
    }

    @Override
    protected void init() {
        Log.e("NewBookReadActivity TAG", "init: 初始化数据");

        mRvBookDesk.setLayoutManager(new LinearLayoutManager(this));
        mBookDeskAdapter = new NewBookReadAdapter(R.layout.item_book_read_case, mEpaperInfoList);
        mRvBookDesk.setAdapter(mBookDeskAdapter);


        bookDeskGridAdapter = new BookDeskGridAdapter(NewBookReadActivity.this, epaperInfoGradeNameBeans);
        grand_name_grid.setAdapter(bookDeskGridAdapter);

        if (DisplayUtils.getWidthInDp(NewBookReadActivity.this) >= 900) {
            grand_name_grid.setNumColumns(6);
            grand_category_grid.setNumColumns(6);
        } else if (DisplayUtils.getWidthInDp(NewBookReadActivity.this) >= 700 && DisplayUtils.getWidthInDp(NewBookReadActivity.this) < 900) {
            grand_name_grid.setNumColumns(5);
            grand_category_grid.setNumColumns(5);
        }else if (DisplayUtils.getWidthInDp(NewBookReadActivity.this) >= 500 && DisplayUtils.getWidthInDp(NewBookReadActivity.this) < 700) {
            grand_name_grid.setNumColumns(4);
            grand_category_grid.setNumColumns(4);
        }else{
            grand_name_grid.setNumColumns(3);
            grand_category_grid.setNumColumns(3);
        }

        mBookDeskAdapter.setOnItemClickListener(new BaseQuickOnItemClickListener() {
            @Override
            public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    if (DoubleClickCheckUtils.vertifyDuration()) {
                        mCurrentNewBookReadBean = mEpaperInfoList.get(position);
                        getLocData(mCurrentNewBookReadBean);
                    }
//                    if (null != epaperInfo) {
//                        if (epaperInfo.getIsExpire() == 1 || epaperInfo.getIsFree() == 1) {
//                            EpaperJumpManager.jumpToCatalog(R.string.go_back, NewBookReadActivity.this, epaperInfo, IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK, -1, epaperInfo.getServerId());
//                        } else {
//                            MeJumpManager.jumpBuyService(NewBookReadActivity.this, R.string.go_back, epaperInfo.getServerId(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
//                        }
//                    }
//                    EpaperJumpManager.jumpToNewReadContent(R.string.go_back, NewBookReadActivity.this, epaperInfo, IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK);
                } catch (Exception e) {

                }
            }
        });
        initCategoryDate();
        getGradeByBookCategoryId();
    }

    @Override
    protected void loadData() {
        mBookmarkId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_BOOKMARK, -1);
        mBookmarkTitle = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
        setTitleText(mBookmarkTitle);
        setGrade();
        mIsRefesh = true;
        mPageIndex = 1;
        if (!NetworkUtils.isOnline()) {
            list_nodata.setVisibility(View.VISIBLE);
            listviewgroup.setVisibility(View.GONE);
        } else {
            list_nodata.setVisibility(View.GONE);
            listviewgroup.setVisibility(View.VISIBLE);
            getGradeByBookmarkId();
            getBookBooksFromNet(mPageIndex);
        }
    }

    private void initCategoryDate() {
        bookCategoryDridAdapter = new BookReadCategoryGridAdapter(NewBookReadActivity.this, mInfoGradeCategoryBean);
        grand_category_grid.setAdapter(bookCategoryDridAdapter);
    }

    /**
     * 填充网络数据
     *
     * @param gradeList
     */
    public void setNetCategoryGrade(List<CategoryBean> gradeList) {
        mInfoGradeCategoryBean = new ArrayList<>();
        CategoryBean categoryBean = new CategoryBean();
        categoryBean.setName("全部");
        categoryBean.setCategoryId(2);
        categoryBean.setId(0);
        categoryBean.setChecked(true);
        mInfoGradeCategoryBean.add(categoryBean);
        for (int i = 0; i < gradeList.size(); i++) {
            CategoryBean item = gradeList.get(i);
            CategoryBean itemGrade = new CategoryBean();
            itemGrade.setName(item.getName());
            itemGrade.setCategoryId(2);
            itemGrade.setId(item.getId());
            itemGrade.setChecked(false);
            mInfoGradeCategoryBean.add(itemGrade);
        }
        bookCategoryDridAdapter.setNewData(mInfoGradeCategoryBean);
    }


    public void getGradeByBookCategoryId() {
        EpaperDao.getInstance().getInteractionCategory(new BaseExtCallBack(NewBookReadActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                if (null != data) {
                    List<InteractionCategoryBean> gradeList = (List<InteractionCategoryBean>) data;
                    Log.e("success data ", GsonUtil.toJson(gradeList));
                    for (InteractionCategoryBean bean : gradeList) {
                        if (bean.getId() == 2) {
                            setNetCategoryGrade(bean.getChild());
                        }
                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    private void getLocData(final NewBookReadBean epaperInfo) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_SECTION_CHAPTER + "0" + epaperInfo.getVersionId() + epaperInfo.getModuleId() + epaperInfo.getcId(), new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        getCatalogueInfo(epaperInfo);
                    }

                    @Override
                    public void failed(Object data) {
                        getCatalogueInfo(epaperInfo);
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取本地DownLoadInfos
                                Log.e("TAG", "data success = " + GsonUtil.toJson(data));
                                NewReadBookNetResultBean info = (NewReadBookNetResultBean) data;
                                buildDownLoadInfo(epaperInfo, info);
                                doClickListener(epaperInfo, mDownLoadInfo);
                            }
//                            loadNetData();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }


    public void doClickListener(final NewBookReadBean bean, final DownLoadInfo downLoadInfo) {
        //开始下载
        if (TextUtils.isEmpty(downLoadInfo.getUrl())) {
            showToastError(R.string.package_no_publish2);
            return;
        }
        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
            case DownloadStatus.STATUS_UPZIPING:
                if (DialogUtil.sdIsFullForDownload(NewBookReadActivity.this, downLoadInfo)) {
                    DialogUtil.showSdFullDialog(NewBookReadActivity.this, downLoadInfo.getSize());
                    return;
                }
                judgeDownloadMethod(downLoadInfo);
                break;
            case DownloadStatus.STATUS_LOADING:
                //                DownLoad.getInstance().pauseTask(downLoadInfo);
                DownLoad.getInstance().resumeTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoad.getInstance().pauseTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_PAUSE:
                if (NetworkUtils.isOnline()) {
                    if (NetworkUtils.isWifiOnline()) {
                        showDownloadDialog();
                        DownLoad.getInstance().resumeTask(downLoadInfo);
                    } else {
                        DialogUtil.showWIFIDialogReadBooK(NewBookReadActivity.this, downLoadInfo);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                }
                break;
            //            case DownloadStatus.STATUS_UPZIPING:
            //                // DownLoad.getInstance().addTask(info);
            //                break;
            case DownloadStatus.STATUS_COMPLETED:
                //新包拆分逻辑增加 资源 versionId,
                //                        String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), bean.getVersionId());
                //服务权限判断，跳转资源详情页

                if (new File(resourcePath).exists()) {
                    downloadComplete(bean, downLoadInfo);
                    //                            EpaperJumpManager.jumpToContent(R.string.go_back, NewContentActivity2.this, downLoadInfo, mServiceId, mEpaperInfo, mEpaperServerList);
                } else {
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    judgeDownloadMethod(downLoadInfo);
                }

                break;
        }

    }

    private void downloadComplete(final NewBookReadBean bean, final DownLoadInfo downLoadInfo) {
        //这里下载完成了
        Log.e(TAG, "下载完成");
        EpaperJumpManager.jumpToNewBookDetailH5Activity(NewBookReadActivity.this, mCurrentNewBookReadBean,  downLoadInfo, 0, 0, NewBookDetailH5Activity.FROM_DESK, "", 0, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_NEW_READ_BOOK);
    }


    private void judgeDownloadMethod(DownLoadInfo downLoadInfo) {
        if (NetworkUtils.isOnline()) {
            if (NetworkUtils.isWifiOnline()) {
                showDownloadDialog();
                DownLoad.getInstance().addTask(downLoadInfo);
            } else {
                DialogUtil.showWIFIDialogReadBooK(
                        NewBookReadActivity.this,
                        downLoadInfo);
            }
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }


    public void showDownloadDialog() {
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean) {
        hideDownloadProgress();
    }

    /**
     * 获取资源下载地址
     */
    private void getCatalogueInfo(final NewBookReadBean epaperInfo) {
        EpaperDao.getInstance().getNewReadBookInfo(epaperInfo.getPackageId(), epaperInfo.getcId(), epaperInfo.getModuleId(), epaperInfo.getVersionId(), new BaseExtCallBack(getBaseApplication(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                try {
                    NewReadBookNetResultBean info = (NewReadBookNetResultBean) data;
                    Log.e("TAG", "date = " + GsonUtil.toJson(info));
                    if (info != null) {
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_SECTION_CHAPTER + "0" + epaperInfo.getVersionId() + epaperInfo.getModuleId() + epaperInfo.getcId(), info);
                        buildDownLoadInfo(epaperInfo, info);
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查更新失败"+getUrl());
                failed("检查更新失败");
            }

            @Override
            public void failed(Object data) {
            }
        });
    }

    private void buildDownLoadInfo(NewBookReadBean bean, NewReadBookNetResultBean info) {
        Log.e("onItemClick 下载的资源 ", GsonUtil.toJson(info));
//        showDownloadProgress("正在下载资源...");
        mDownLoadInfo = new DownLoadInfo();
        mDownLoadInfo.setUrl(info.getDownLoadUrl());
        mDownLoadInfo.setBookId(bean.getPackageId());
        mDownLoadInfo.setChapterId(info.getcId());
        mDownLoadInfo.setChapterId(info.getcId());
        mDownLoadInfo.setChapterName(info.getcName());
        mDownLoadInfo.setHash(info.getHash());
        mDownLoadInfo.setIsFree(1);
        mDownLoadInfo.setSavePath(FileUtil.getSavePathByUrl(NewBookReadActivity.this, info.getDownLoadUrl()));
        //新旧包结构区分
        mDownLoadInfo.setType(CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);
        mDownLoadInfo.setResourceName(info.getcName());
        mDownLoadInfo.setResourceType(ModuleContent.ResourceType.RESOURCE_TYPE_ONLINE_NEW_READ);
        mDownLoadInfo.setModuleId(String.valueOf(bean.getModuleId()));
        mDownLoadInfo.setVersionId(bean.getVersionId());
        String fileSize = info.getFileSize();
        if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
            mDownLoadInfo.setSize(fileSize.split(" ")[0]);
        }
        mDownLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
        DownLoadDB.insertDetail(mDownLoadInfo);

        doClickListener(bean, mDownLoadInfo);
    }

    /**
     * 获取书籍
     *
     * @param pageIndex 页码
     */
    public void getBookBooksFromNet(int pageIndex) {
        CWLog.e(TAG,"getBookBooksFromNet pageIndex " + pageIndex );
        EpaperDao.getInstance().getInteractionList(gradeId,  subCategoryId, categoryId,pageIndex, mPageSize, new BaseExtCallBack(NewBookReadActivity.this) {
            @Override
            public void failed(Object data) {
                super.failed(data);
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {
                Log.e("getBookBooksFromNet ", GsonUtil.toJson(data));
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
                try {
                    if (data != null && data instanceof NewBookReadNetBean) {
                        NewBookReadNetBean bookMarkPageInfo = (NewBookReadNetBean) data;

                        List<NewBookReadBean> epaperInfoList = bookMarkPageInfo.getList();

                        if (mIsRefesh) {
                            if (epaperInfoList != null && epaperInfoList.size() >= 0) {
                                mEpaperInfoList = epaperInfoList;
                                mBookDeskAdapter.setNewData(mEpaperInfoList);
                            }
                        } else {
                            if (epaperInfoList != null && epaperInfoList.size() >= 0) {
                                mEpaperInfoList.addAll(epaperInfoList);
                                mBookDeskAdapter.addData(epaperInfoList);
                            }
                        }

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
    }

    /**
     * 获取书籍
     *
     * @param gradeId       年级id
     * @param isNeedRefresh 是否选择年级刷新数据
     */
    public void getServiceProductsByIdClassids(int gradeId, final boolean isNeedRefresh) {
        this.gradeId = gradeId;
        if (isNeedRefresh) {
            onRefresh();
        }
    }


    public void getServiceProductsByIdCategoryids(int child, int categoryId, final boolean isNeedRefresh) {
        this.categoryId = child;
        this.subCategoryId = categoryId;
        if (isNeedRefresh) {
            onRefresh();
        }
    }

    /**
     * 获取书籍包含的年级列表
     */
    public void getGradeByBookmarkId() {

        EpaperDao.getInstance().getGradeByBookmarkId(EApplication.BRAND_ID, mBookmarkId, new BaseExtCallBack(NewBookReadActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                if (null != data) {
                    List<GradeBean> gradeList = (List<GradeBean>) data;
                    setNetGrade(gradeList);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    /**
     * 填充网络数据
     *
     * @param gradeList
     */
    public void setNetGrade(List<GradeBean> gradeList) {
        epaperInfoGradeNameBeans = new ArrayList<>();
        EpaperInfoGradeNameBean epaperInfoGradeNameBean = new EpaperInfoGradeNameBean("全部", 0, true);
        epaperInfoGradeNameBean.setGradeName("全部");
        epaperInfoGradeNameBean.setGradeId(0);
        epaperInfoGradeNameBean.setChecked(true);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean);
        for (int i = 0; i < gradeList.size(); i++) {
            GradeBean item = gradeList.get(i);
            EpaperInfoGradeNameBean itemGrade = new EpaperInfoGradeNameBean(item.getGradeName(), item.getGrade());
            epaperInfoGradeNameBeans.add(itemGrade);
        }
        bookDeskGridAdapter.setNewData(epaperInfoGradeNameBeans);
    }

    /**
     * 初始化本地数据
     */
    public void setGrade() {
        epaperInfoGradeNameBeans = new ArrayList<>();
        EpaperInfoGradeNameBean epaperInfoGradeNameBean = new EpaperInfoGradeNameBean("全部", 0, true);
        epaperInfoGradeNameBean.setGradeName("全部");
        epaperInfoGradeNameBean.setGradeId(0);
        epaperInfoGradeNameBean.setChecked(true);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean7 = new EpaperInfoGradeNameBean("七年级", 1107);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean8 = new EpaperInfoGradeNameBean("八年级", 1108);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean9 = new EpaperInfoGradeNameBean("九年级", 1109);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean14 = new EpaperInfoGradeNameBean("其他", 333333);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean7);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean8);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean9);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean14);
        bookDeskGridAdapter.setNewData(epaperInfoGradeNameBeans);
    }

    @Override
    public void onRefresh() {
        mIsRefesh = true;
        mPageIndex = 1;
        getBookBooksFromNet(mPageIndex);
    }

    @Override
    public void onLoadMore() {
        mIsRefesh = false;
        mPageIndex++;
        getBookBooksFromNet(mPageIndex);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
                    onRefresh();
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }


    @Override
    protected void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        if (info != null) {
            mDownLoadInfo = info;
            dealCircleProgress(info);
        }

    }

    private void dealCircleProgress(final DownLoadInfo downLoadInfo) {
        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideDownloadHorizontalProgressBar();
                hideCancelButtonOfDownloadProgress();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo);

                Log.e(TAG, "dealCircleProgress: " + resourcePath);
                Log.e(TAG, "dealCircleProgress exists : " + new File(resourcePath).exists());
                if (new File(resourcePath).exists()) {
                    hideDownloadProgress();
                    downloadComplete(mCurrentNewBookReadBean, downLoadInfo);

                } else {
                    //这个状态表示没有下载成功
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    ThreadTask.getInstance().executorDBThread(new Runnable() {
                        public void run() {
                            DownLoadDB.insertDetail(downLoadInfo);
                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                    hideDownloadProgress();
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                }
                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                //                Log.e(TAG, "onEventMainThread STATUS_DOWNLOADING: "+downLoadInfo.getChapterName()+"  "+downLoadInfo.getResourceName()+"  progress"+downLoadInfo.getProgress() );
                if (HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mDownLoadInfo)) {
                    updateDownloadProgress(downLoadInfo.getProgress());
                }
                break;
        }
    }


}

